<template>
  <div
    v-loading="loading"
    style="display: flex; flex-direction: column; flex: 1; height: 100%"
    element-loading-text="加载中..."
  >
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="addData"> 添加视频 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeAll(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <!-- 关键词搜索 -->
      <div class="search">
        <el-input
          clearable
          v-model="name"
          placeholder="关键词搜索"
          class="input-with"
          @keyup.enter="getList"
          @clear="getList"
        />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>

    <!-- 表格内容 -->
    <div class="table">
      <el-table
        border
        stripe
        resizable
        :data="tableData"
        @selection-change="handleChange"
        ref="tableDom"
        height="100%"
        style="position: absolute"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column show-overflow-tooltip type="index" label="序号" width="55" />
        <el-table-column show-overflow-tooltip prop="name" label="视频名称" max-width="230">
          <template #default="scope">
            <div class="part flex-justify-between">
              <div class="name">{{ scope.row.name }}</div>
              <el-popover placement="right" :width="200" trigger="hover">
                <el-image style="width: 100%; height: 120px" :src="scope.row.image" fit="contain">
                  <template #error>
                    <div class="image-slot">
                      <el-icon>
                        <icon-picture />
                      </el-icon>
                    </div>
                  </template>
                </el-image>
                <template #reference>
                  <el-icon size="20">
                    <Picture />
                  </el-icon>
                </template>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="knowledgeType"
          label="知识库类型"
          max-width="230"
        />
        <el-table-column show-overflow-tooltip prop="status" label="状态" width="80">
          <template #default="scope">
            <HStatus v-if="scope.row.status === false">启用</HStatus>
            <HStatus v-if="scope.row.status === true" type="info">禁用</HStatus>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="clickNum" label="点击数" width="80" />
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="150" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="150" />
        <el-table-column fixed="right" label="操作" width="100">
          <template #default="scope">
            <el-space :size="0" :spacer="spacer">
              <HLink @click="videoView(scope.row)">预览</HLink>
              <HLink @click="videoDetail(scope.row)">详细</HLink>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <div class="footer">
      <Pagination
        ref="pagination"
        :list_total="total"
        @size-change="getList"
        @current-change="getList"
      />
    </div>

    <!-- 添加/编辑  视频弹窗 -->
    <HModal v-model="addDialog" :width="550">
      <template #header>
        <div class="my-header">
          <h3 class="title">{{ dialogTitle }}</h3>
        </div>
      </template>
      <div v-loading="dialogLoading" element-loading-text="加载中...">
        <div class="form-text">
          <el-form
            label-width="100"
            ref="formRef"
            :rules="rules"
            :model="form"
            class="form_content"
            @validate="handleFormValidate"
          >
            <!--视频名称-->
            <el-form-item
              label="视频名称"
              :class="{ form_item: formValidateResult, validate_fail: !formValidateResult }"
              prop="name"
            >
              <el-input v-model="form.name" class="item-input" clearable placeholder="请输入名称" />
            </el-form-item>

            <!--视频状态-->
            <el-form-item label="视频状态" class="radio_form_item">
              <el-radio-group v-model="form.status">
                <div class="radio_container">
                  <el-radio :value="false">
                    <span class="bg_text">启用</span>
                  </el-radio>
                  <el-radio :value="true">
                    <span class="bg_text">禁用</span>
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>

            <!--所属知识库类型-->
            <el-form-item label="所属知识库类型" class="form_item">
              <KnowledgeMultiple
                ref="knowledgeMultipleRef"
                :oldKnowledgeTypeVo="form.knowledgeTypeVos"
              />
            </el-form-item>

            <!--视频封面-->
            <el-form-item label="视频封面" class="form_item">
              <div class="upload-card">
                <el-upload
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="uploadvideoFile"
                  accept="image/*"
                >
                  <el-image style="width: 100px; height: 100px" :src="videoImage" fit="contain">
                    <template #error>
                      <div class="image-slot">
                        <el-icon>
                          <Plus />
                        </el-icon>
                      </div>
                    </template>
                  </el-image>
                </el-upload>
              </div>
            </el-form-item>

            <!--视频文件-->
            <el-form-item label="视频文件" class="form-item">
              <el-upload
                class="upload-demo"
                multiple
                accept=".mp4"
                :auto-upload="false"
                :on-remove="removeVideoUrl"
                v-model:file-list="fileList"
              >
                <template #trigger>
                  <HPlainButton>点击上传</HPlainButton>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footerLeft>
        <HPlainBgButton
          v-show="dialogTitle == '编辑视频'"
          type="error"
          is-modal
          @click="changeAll(4)"
          >删除</HPlainBgButton
        >
      </template>

      <template #footerRight>
        <HButton @click="saveData(formRef)" is-modal type="primary">保存</HButton>
        <HButton @click="onClose" is-modal>取消</HButton>
      </template>
    </HModal>

    <!-- 视频预览弹窗 -->
    <HModal v-model="viewDialog" title="视频预览" :width="800">
      <div class="title flex-justify-between">
        <span class="name">{{ form.name }}</span>
        <p>更新时间：{{ upTime }}</p>
      </div>
      <div class="content flex-center">
        <template v-if="videoUrl.length != 0">
          <video
            class="video-item"
            v-for="item in videoUrl"
            :key="item.path"
            :src="item.path"
            controls
            loop
            :poster="videoFile"
          ></video>
        </template>
        <el-empty v-else />
      </div>
    </HModal>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, markRaw, h } from 'vue'
  import { UploadFile, UploadProps, FormInstance, ElDivider, FormItemProp } from 'element-plus'
  import {
    Search,
    Plus,
    Picture as IconPicture,
    Delete,
    Warning,
    Picture,
    ArrowDown,
    CircleCheck,
  } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import Pagination from '@/components/Pagination/index.vue'
  import KnowledgeMultiple from '@/components/Knowledge/knowledgeMultiple.vue'
  import { knowledgeAnnexUpload, deleteFile, videoUpload } from '@/api/upload'
  import { videoList, videoSave, videoInfo, videoDisable, videoDelete } from '@/api/knowledge'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import { HModal } from '@/components/common'

  /**
   * 表单验证结果
   */
  const formValidateResult = ref(true)

  /**
   * 表单验证事件
   */
  const handleFormValidate = (prop: FormItemProp, isValid: boolean) => {
    formValidateResult.value = isValid
  }

  /**
   * 弹窗关闭事件
   */
  const onClose = () => {
    addDialog.value = false
    formValidateResult.value = true
  }

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  const loading = ref(false)
  const name = ref('') // 名称
  const tableData = ref([]) // 列表数据
  const tableDom = ref() // 列表dom
  const pagination = ref() // 分页dom
  const total = ref(0) // 总数目

  const addDialog = ref(false)
  const viewDialog = ref(false)
  const dialogTitle = ref('')
  const dialogLoading = ref(false)
  const upTime = ref('')

  const formRef = ref<FormInstance>()
  const knowledgeMultipleRef = ref() // 知识库ref对象

  const form = reactive({
    id: null,
    name: '',
    image: '',
    status: false,
    delRelationIds: [], // 删除知识库的关联对象ID
    knowledgeTypeVos: [
      // 知识库分类对象
      {
        id: '', // 关联对象表ID，新增不必传
        knowledgeTypeId: '', // 知识库分类ID
      },
    ],
    delVideoPaths: [], // 删除的视频内容路径
    videoPaths: [], // 	视频内容路径
  })

  const videoImage = ref()
  const videoFile = ref()

  const fileList = ref([])
  const videoUrl = ref([])

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入视频名称', trigger: 'blur' }],
  })

  // 获取表格勾选数据
  const selecttion = ref([])
  const handleChange = (val: any) => {
    if (val.length != 0) {
      val.forEach((item) => {
        if (selecttion.value.indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 获取列表数据
  const getList = async () => {
    loading.value = true
    const data = {
      limit: pagination.value.size,
      name: name.value,
      page: pagination.value.current,
    }
    await videoList(data).then((res) => {
      tableData.value = res.data.data.rows
      total.value = parseInt(res.data.data.total)
    })
    loading.value = false
  }

  // 添加视频
  const addData = async () => {
    dialogTitle.value = '添加视频'
    addDialog.value = true
    videoFile.value = ''
    videoImage.value = ''
    form.delVideoPaths = []
    form.id = null
    form.image = ''
    form.name = ''
    form.status = false
    form.videoPaths = []
  }

  // 上传图片
  const uploadvideoFile: UploadProps['onChange'] = (uploadFile: UploadFile) => {
    if (!uploadFile.raw.type.includes('image')) {
      ElMessage.error('只能上传图片')
      return false
    }
    if (uploadFile.raw.size / 1024 / 1024 > 50) {
      ElMessage.error('图片大小不能超过50M!')
      return false
    }
    videoFile.value = uploadFile.raw
    videoImage.value = window.URL.createObjectURL(uploadFile.raw!)
  }

  // 删除视频
  const removeVideoUrl = (uploadFile: UploadFile) => {
    form.videoPaths.forEach((item) => {
      if (item.path == uploadFile.url) {
        form.delVideoPaths.push({
          id: item.id,
          path: item.path,
        })
      }
    })
  }

  // 编辑视频
  const videoDetail = async (obj: any) => {
    addDialog.value = true
    dialogLoading.value = true
    dialogTitle.value = '编辑视频'
    videoFile.value = ''
    fileList.value = []
    await videoInfo(obj.id).then((res) => {
      const data = res.data.data.row
      form.id = data.id
      form.name = data.name
      form.image = data.image
      videoImage.value = data.image
      form.status = data.status
      form.videoPaths = data.videoPaths
      form.knowledgeTypeVos = data.knowledgeTypeVos
      if (data.videoPaths.length != 0) {
        data.videoPaths.forEach((item, i) => {
          fileList.value.push({
            name:
              item.path.substring(item.path.lastIndexOf('/') + 1, item.path.lastIndexOf('_')) +
              '.mp4',
            url: item.path,
          })
        })
      }
    })
    dialogLoading.value = false
  }

  // 保存数据
  const saveData = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        saveMethod(form)
      }
    })
  }

  // 保存的方法
  const saveMethod = async (data) => {
    // 上传图片
    if (videoFile.value) {
      const files = []
      files.push(videoFile.value)
      if (files.length != 0) {
        await knowledgeAnnexUpload(files).then((res) => {
          if (videoImage.value.startsWith('blob') && form.image != '') {
            deleteFile([form.image]).then()
          }
          form.image = res.data.data.rows[0]
        })
      }
    }
    // 上传视频
    const files = []
    if (fileList.value.length != 0) {
      fileList.value.forEach((item) => {
        if (item.raw) {
          files.push(item.raw)
        }
      })
      if (files.length != 0) {
        await videoUpload(files).then((res) => {
          res.data.data.rows.forEach((item) => {
            form.videoPaths.push({
              path: item,
            })
          })
        })
      }
    }
    form.knowledgeTypeVos = knowledgeMultipleRef.value.getKnowledgeSelectVal().value
    form.delRelationIds = knowledgeMultipleRef.value.getDeleteKnowledgeSelectVal().value
    dialogLoading.value = true
    videoSave(form).then((res) => {
      dialogLoading.value = false
      if (res.data.isError)
        ElMessage({
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          duration: 2000,
        })
      if (res.data.success == true) {
        addDialog.value = false
        getList()
      }
    })
  }

  // 视频预览
  const videoView = async (obj: any) => {
    viewDialog.value = true
    dialogLoading.value = true
    await videoInfo(obj.id).then((res) => {
      form.name = res.data.data.row.name
      videoImage.value = res.data.data.row.image
      upTime.value = obj.updateTime
      videoUrl.value = res.data.data.row.videoPaths
    })
    dialogLoading.value = false
  }

  // 修改状态的方法
  const changeMethod = (type, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的视频`,
        type: 'warning',
        duration: 2000,
      })
      return
    }
    ElMessageBox({
      type: type == '删除' ? 'error' : 'warning',
      title: '提示',
      icon: type == '删除' ? markRaw(Delete) : markRaw(Warning),
      message: `确认${type}选中的视频?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        await method(arr, status).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
        })
      } else {
        await method(arr).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
          if (dialog != '') {
            addDialog.value = false
          }
        })
      }
      selecttion.value = []
      tableDom.value.clearSelection()
      getList()
    })
  }

  // 批量启用/禁用/删除
  const changeAll = (n) => {
    if (n == 1) {
      changeMethod('启用', videoDisable, selecttion.value, false, '')
    }
    if (n == 2) {
      changeMethod('禁用', videoDisable, selecttion.value, true, '')
    }
    if (n == 3) {
      changeMethod('删除', videoDelete, selecttion.value, 3, '')
    }
    if (n == 4) {
      changeMethod('删除', videoDelete, [form.id], 3, 1)
    }
  }

  defineExpose({ getList })
</script>

<style scoped lang="scss">
  @import './VideoCard.scss';
</style>
